package tech.treec.smartlight.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.young.mylib.db.dao.DeviceDao;
import com.young.mylib.db.entity.DeviceEntity;
import com.young.mylib.utils.JsonUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import tech.treec.smartlight.R;
import tech.treec.smartlight.adapter.MyAdapter;
import tech.treec.smartlight.callback.ButtonClickCallback;

import static tech.treec.smartlight.Constants.ACTION_BASE_RECEIVE;
import static tech.treec.smartlight.Constants.ACTION_LINKAGE_CONFIG_RECEIVE;
import static tech.treec.smartlight.Constants.ACTION_MQTT_RESTART_SERVICE;
import static tech.treec.smartlight.Constants.ACTION_REQUEST_LINKAGE_CONFIG;

public class DeviceActivity extends BaseActivity {
    private final static int HANDLER_TOOLBAR_MENU = 1000, HANDLER_REF_LIST = 1001;
    private final static String TAG = "DeviceActivity";
    @BindView(R.id.my_gride_view)
    GridView gridView;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private MsgReceiver msgReceiver;
    List<Map<String, String>> list = new ArrayList<>();
    MyAdapter adapter;

    @Override
    protected int setLayoutID() {
        return R.layout.activity_switch;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setSupportActionBar(toolbar);
    }

    @Override
    protected void initView() {
        toolbar.setTitle(R.string.app_name);
//        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
//        }
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
    }

    @Override
    protected void loadData() {
        gridView.setNumColumns(4);
        //自定义BaseAdapter适配器
        adapter = new MyAdapter(this, R.layout.switch_item, list, new ButtonClickCallback() {
            @Override
            public void onClick(String msg,int pos) {

            }
        });
        gridView.setAdapter(adapter);

        if (msgReceiver == null) {
            msgReceiver = new MsgReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION_LINKAGE_CONFIG_RECEIVE);

            registerReceiver(msgReceiver, intentFilter);
        }
        loadDevice();
    }

    private void loadDevice() {
        List<DeviceEntity> array = DeviceDao.findAll();
        list.clear();

        for (DeviceEntity entity : array) {
            Map map = new HashMap();
            map.put("name", entity.deviceName);
            map.put("img", R.drawable.ic_launcher_background);
            list.add(map);
        }

        adapter.notifyDataSetChanged();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed(); // 调用onBackPressed()方法来处理返回操作
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    Handler loadHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //更新界面
            if (msg.what == HANDLER_REF_LIST) {
                String str = msg.obj.toString();
                JSONObject json = JsonUtils.toJsonObject(str);
                JSONArray result = json.getJSONArray("result");
                list.clear();
                for (Object _jo : result) {
                    JSONObject jo = JsonUtils.toJsonObject(_jo.toString());
                    Log.i(TAG, jo.toJSONString());
                    Map map = new HashMap();
                    map.put("name", jo.getString("name"));
                    map.put("img", R.drawable.ic_launcher_background);
                    list.add(map);
                }
                adapter.notifyDataSetChanged();

            }
            if (msg.what == HANDLER_TOOLBAR_MENU) {

                if ((int) msg.obj == R.id.action_dev) {
                    Log.i(TAG, "设备管理" + msg.obj);
                }
                if ((int) msg.obj == R.id.action_sys) {
                    Log.i(TAG, "系统管理" + msg.obj);

                    Intent intent = new Intent(DeviceActivity.this, SettingsActivity.class);
                    startActivity(intent);
                }
                if ((int) msg.obj == R.id.action_log) {
                    Log.i(TAG, "应用日志" + msg.obj);
                    Intent intent = new Intent(DeviceActivity.this, LogActivity.class);
                    startActivity(intent);
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (msgReceiver != null) {
            unregisterReceiver(msgReceiver);
            msgReceiver = null;
        }

    }

    private class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "消息到达");
            try {
                String msg = intent.getStringExtra("msg");

                Message _msg = new Message();
                _msg.what = HANDLER_REF_LIST;
                _msg.obj = msg;


                loadHandler.sendMessage(_msg);

            } catch (Exception e) {
                Log.e(TAG, "MsgReceiver error: " + e.getMessage());
            }
        }
    }
}